package com.modular.swagger;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.config.BeanPostProcessor;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.lang.NonNull;
import org.springframework.util.ReflectionUtils;
import org.springframework.web.servlet.mvc.method.RequestMappingInfoHandlerMapping;
import springfox.documentation.spring.web.plugins.WebMvcRequestHandlerProvider;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebFlux;
import springfox.documentation.swagger2.annotations.EnableSwagger2WebMvc;

import java.lang.reflect.Field;
import java.util.List;

@Configuration
public class SwaggerEnhanceConfig {
    public SwaggerEnhanceConfig() {
    }

    @ConditionalOnClass({WebMvcRequestHandlerProvider.class, RequestMappingInfoHandlerMapping.class})
    @ConditionalOnMissingBean(
            name = {"customSpringfoxHandlerProviderBeanPostProcessor"}
    )
    @Bean({"customSpringfoxHandlerProviderBeanPostProcessor"})
    public BeanPostProcessor springfoxHandlerProviderBeanPostProcessor() {
        return new BeanPostProcessor() {
            public Object postProcessAfterInitialization(@NonNull Object bean, @NonNull String beanName) throws BeansException {
                if (bean instanceof WebMvcRequestHandlerProvider) {
                    this.customizeSpringfoxHandlerMappings(this.getHandlerMappings(bean));
                }

                return bean;
            }

            private <T extends RequestMappingInfoHandlerMapping> void customizeSpringfoxHandlerMappings(List<T> mappings) {
                List<T> copy = mappings.stream().filter((mapping) -> {
                    return mapping.getPatternParser() == null;
                }).toList();
                mappings.clear();
                mappings.addAll(copy);
            }

            private List<RequestMappingInfoHandlerMapping> getHandlerMappings(Object bean) {
                try {
                    Field field = ReflectionUtils.findField(bean.getClass(), "handlerMappings");

                    assert field != null;

                    field.setAccessible(true);
                    return (List)field.get(bean);
                } catch (IllegalAccessException | IllegalArgumentException var3) {
                    throw new IllegalStateException(var3);
                }
            }
        };
    }
}
